<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>宇成建筑</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="../statics/css/font.css">
    <link rel="stylesheet" href="../statics/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../statics/css/xadmin.css">
    <link rel="stylesheet" href="../statics/css/style.css">
    <style>
        .layui-table td, .layui-table th {
            min-width: 40px !important;
        }

        .layui-table td, .layui-table th {
            padding: 5px !important;
        }

        th:first-child, td:first-child {
            text-align: center;
        }
        .label{
            font-size: 14px;
        }
        .label p {
            display: inline-block;
            line-height: 30px;
            margin-left: 20px;
        }
    </style>
</head>

<body class='labelAuto'>
<div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="welcome.html">首页</a>
            <a href="javascript:;">施工管理</a>
            <a href="javascript:;">施工分账</a>
            <a class="areaName" href="javascript:;"></a>
            <a class="sectionName" href="javascript:;"></a>
            <a href="javascript:;">施工分账记录</a>
            <a>
                <cite><span class="groupName"></span> 施工量价编辑</cite>
            </a>
        </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right;margin-right:10px"
       onclick="window.history.go(-1)" title="后退">
        <i class="iconfontBlod" style="line-height:30px">&#xe74f;</i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <h2 style="text-align: center">班组施工项分账记录表<button type="button" class="layui-btn layui-btn-xs" style="margin:0 5px;">展开</button></h2>
                    <form class="layui-form" style="overflow: scroll;">
                        <table class="layui-table" id="assignment" lay-filter="test" style="min-width:1350px;">
                            <thead>
                            <tr>
                                <th style="width:50px;text-align: center">编号</th>
                                <th style="width:180px">施工项</th>
                                <th style="width:80px">工程量</th>
                                <th style="width:90px">单位</th>
                                <th style="width:80px">单价</th>
                                <th style="width:90px">总价</th>
                                <th style="width:360px">备注</th>
                                <th style="width:100px">完成时间</th>
                                <th style="width:70px">录入批次</th>
                                <th style="width:60px">录入人</th>
                                <th style="width:70px">状态</th>
                                <th style="width:90px">操作</th>
                            </tr>
                            </thead>
                            <tbody class="layui-hide"></tbody>
                            <tfoot class="layui-table-total">
                            <tr>
                                <th>合计</th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th id="total" data-total=""></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
                <div class="layui-card-body">
                    <h2 style="text-align: center">班组人员-入账明细单</h2>
                    <form class="layui-form" style="overflow: scroll;">
                        <table class="layui-table" id="accounts" lay-filter="test" style="min-width:1000px;">
                            <thead>
                            <tr>
                                <th style="width:50px;text-align: center">编号</th>
                                <th style="width:100px">姓名</th>
                                <th style="width:80px">工号</th>
                                <th style="width:100px">分账金额</th>
                                <th style="width:90px">分账时间</th>
                                <th style="width:90px">记录时间</th>
                                <th style="width:320px">备注</th>
                                <th style="width:80px">录入人</th>
                                <th style="width:80px">状态</th>
                                <th style="width:90px">操作</th>
                            </tr>
                            </thead>
                            <tbody class=""></tbody>
                            <tfoot class="layui-table-total">
                            <tr>
                                <th>合计</th>
                                <th></th>
                                <th></th>
                                <th id="totalAccounts"></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
                <div class="layui-card-body layui-row">
                    <div class="layui-col-md4"></div>
                    <div class="layui-col-md4" style="text-align: center">
                        <button class='addMember layui-btn' type="button">添加分账人员</button>
                        <button class='save layui-btn' type="button">保存分账</button>
                    </div>
                    <div class="layui-col-md4"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="../statics/plugins/layui/layui.js" charset="utf-8"></script>
<script src='../statics/plugins/jQuery-3.2.1/jquery-3.2.1.min.js'></script>
<script type="text/javascript" src="../statics/plugins/X-admin/xadmin.js"></script>
<script type="text/javascript" src="../statics/js/public.js?v=1129"></script>
<script type="text/javascript">
    layui.use(['form', 'layer', "table", "laydate"], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        // $('form').css('height', (window.innerHeight - 165) + 'px');
        var projectId = getParam('projectId');
        var areaId = getQueryString('areaId');
        var sectionId = getQueryString('sectionId');
        var professionId = getQueryString('professionId');
        var groupId = getQueryString('groupId');
        var batch = getQueryString('batch');
        var areaName = localStorage.getItem('areaName');
        var sectionName = localStorage.getItem('sectionName');
        var groupName = localStorage.getItem('groupName');
        $('.layui-breadcrumb a.areaName').html(areaName);
        $('.layui-breadcrumb a.sectionName').html(sectionName);
        $('.layui-breadcrumb span.groupName').html(groupName);

        var data = [];//保存后台传回来的分账数据
        $.ajax({
            url: url + "/project/project/groupAssignment",
            type: "POST",
            async: false,
            data: {
                projectId: projectId,
                sectionId: sectionId,
                professionId: Number(professionId),
                groupId: Number(groupId),
                batch: batch,
                token: getToken()
            },
            success: function (r) {
                data = r.data
            }
        });
        var tableHtml = '';
        var total = 0;
        for (let i = 0; i < data.length; i++) {
            total += Number(data[i].totalPrice);
            tableHtml += `<tr data-id=${data[i].id}>
                            <td class="index">${i + 1}</td>
                            <td>${data[i].assignmentName == null ? "" : data[i].assignmentName}</td>
                            <td>
                                ${numberFormat(data[i].amount)}
                            </td>
                            <td>${data[i].unitName == null ? "" : data[i].unitName}</td>
                            <td>
                                ${numberFormat(data[i].price, 'currency')}
                            </td>
                            <td class="totalPrice" data-total=${data[i].totalPrice}>
                                ${numberFormat(data[i].totalPrice, 'currency')}
                            </td>
                            <td>
                                ${data[i].remark === 'null' ? '' : data[i].remark}
                            </td>
                            <td>
                                ${data[i].completeTime ? data[i].completeTime.substr(0, 10) : ''}
                            </td>
                            <td>
                                ${data[i].batch === 0 ? '未保存' : data[i].batch}
                            </td>
                            <td>
                                ${data[i].adminName ? data[i].adminName : ''}
                            </td>
                            <td>${approvalStatus(data[i].status)}</td>
                            <td>
                                ${data[i].status != 1 && data[i].status != 2 ? "<button class='remove layui-btn layui-btn-danger' type='button'>删除</button>" : ''}
                            </td>
                        </tr>`

        }
        $('#assignment tbody').append(tableHtml);
        $('#total').data('total',total);
        $('#total').empty().html(numberFormat(total, 'currency'));
        $('.layui-card-body:first').append(labelStatistics(data));

        var accounts = [];//保存后台传回来的分账数据
        var members = [];//保存后台传回来的班组人员数据
        $.ajax({
            url: url + "/project/project/groupAccounts",
            type: "POST",
            async: false,
            data: {
                projectId: projectId,
                sectionId: sectionId,
                professionId: Number(professionId),
                groupId: Number(groupId),
                batch: batch,
                token: getToken()
            },
            success: function (r) {
                accounts = r.data
            }
        });
        var tableHtml1 = '';
        var totalAccounts = 0;
        if (accounts.length > 0) {
            for (let i = 0; i < accounts.length; i++) {
                totalAccounts += Number(accounts[i].account);
                if (accounts[i].status == 1 || accounts[i].status == 2) {
                    tableHtml1 += `<tr data-id=${accounts[i].id}>
                            <td class="index">${i + 1}</td>
                            <td>${accounts[i].employeeName == null ? "" : accounts[i].employeeName}</td>
                            <td>
                                ${accounts[i].jobNumber}
                            </td>
                            <td class="totalAccounts" data-total=${accounts[i].account}>${numberFormat(accounts[i].account, 'currency')}</td>
                            <td>
                                ${accounts[i].separateTime.substr(0, 10)}
                            </td>
                            <td>
                                ${accounts[i].createTime.substr(0, 10)}
                            </td>
                            <td>
                                ${accounts[i].remark == null ? '' : accounts[i].remark}
                            </td>
                            <td>
                                ${accounts[i].adminName ? accounts[i].adminName : ''}
                            </td>
                            <td>${approvalStatus(accounts[i].status)}</td>
                            <td>
                                ${accounts[i].status != 1 && accounts[i].status != 2 ? "<button class='remove layui-btn layui-btn-danger' type='button'>删除</button>" : ''}
                            </td>
                        </tr>`
                } else {
                    tableHtml1 += `<tr class="new" data-id='${accounts[i].id}'>
                        <td class="index">${i + 1}</td>
                        <td class="employeeId" data-id="${accounts[i].employeeId}">${accounts[i].employeeName == null ? "" : accounts[i].employeeName}</td>
                        <td>${accounts[i].jobNumber == null ? "" : accounts[i].jobNumber}</td>
                        <td class="totalAccounts" data-total="${accounts[i].account}"><input class="layui-input" type='number' name='account' min="0" value="${accounts[i].account}"></td>
                        <td>${accounts[i].separateTime.substr(0, 10)}</td>
                        <td>${accounts[i].createTime.substr(0, 10)}</td>
                        <td><textarea class='layui-input' name="remark">${accounts[i].remark == null ? '' : accounts[i].remark}</textarea>
                        </td>
                        <td>${accounts[i].adminName ? accounts[i].adminName : ''}</td>
                        <td>${approvalStatus(accounts[i].status)}</td>
                        <td>${accounts[i].status != 2 && accounts[i].status != 3 ? "<button class='remove layui-btn layui-btn-danger' type='button'>删除</button>" : ''}</td>
                    </tr>`
                }
            }
        }else{
            $.ajax({
                url: url + "/hrm/group/memberLists",
                type: "POST",
                async: false,
                data: {
                    groupId: Number(groupId),
                    token: getToken()
                },
                success: function (r) {
                    members = r.data
                }
            });

            for (let i = 0; i < members.length; i++){
                tableHtml1 += `<tr class="new" data-id=''>
                        <td class="index">${i + 1}</td>
                        <td class="employeeId" data-id="${members[i].employeeId}">${members[i].employeeName == null ? "" : members[i].employeeName}</td>
                        <td>${members[i].jobNumber == null ? "" : members[i].jobNumber}</td>
                        <td class="totalAccounts" data-total=""><input class="layui-input" type='number' name='account' min="0" value=""></td>
                        <td></td>
                        <td></td>
                        <td><textarea class='layui-input' name="remark"></textarea>
                        </td>
                        <td></td>
                        <td></td>
                        <td><button class='remove layui-btn layui-btn-danger' type='button'>删除</button></td>
                    </tr>`
            }
        }
        $('#accounts tbody').append(tableHtml1);
        $('#totalAccounts').empty().html(numberFormat(totalAccounts, 'currency'));
        $('#accounts tr').each(function(){
            let input_id = $(this).find('input[name=separateTime]').attr('id');
            laydate.render({elem: `#${input_id}`,max:0});
        });
        form.render();

        $('h2 button').on('click',function(){
            if ($('#assignment tbody').hasClass('layui-hide')){
                $('#assignment tbody').removeClass('layui-hide');
                $('h2 button').text('缩回');
            }else{
                $('#assignment tbody').addClass('layui-hide');
                $('h2 button').text('展开');
            }
        });

        //删除当前行
        $('body').on('click','button.remove',function(){
            let elem = $(this);
            let id = $(this).parent().parent().data('id');
            if (id != ''){
                layer.open({
                    type: 1,
                    title: "删除",
                    area: ["40%", '30%'],
                    content:`
                        <form class="layui-form layerOpen" action="">
                            <div class="layui-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">确定删除吗？</label>
                                </div>
                            </div>
                        </form>
                    `,
                    btn: ['确定','取消'],
                    skin: 'my-skin',
                    yes:function(){
                        $.ajax({
                            url: url + '/project/project/delAccount',
                            type: 'post',
                            data: {
                                id: id,
                                token: getParam('token')
                            },
                            async: false,
                            dataType: 'json',
                            success: function (r) {
                                tips('删除',r);
                                //移除当前行
                                elem.parent().parent().remove();
                                //更新index
                                let index = $('tbody tr').length;
                                $('#accounts td.index').each(function(i){
                                    $(this).empty().html(i+1)
                                });
                                totalPrice();
                                setTimeout(function(){
                                    layer.closeAll()
                                })
                            }
                        })
                    }
                })
            }else{
                //移除当前行
                elem.parent().parent().remove();
                //更新index
                let index = $('tbody tr').length;
                $('#accounts td.index').each(function(i){
                    $(this).empty().html(i+1)
                });
                totalPrice();
            }
        });

        $('button.addMember').on('click',function(){
            layer.open({
                type: 1,
                title: "添加分账人",
                area: ['40%', '50%'],
                content: `
                    <form class='layui-form layerOpen' lay-filter="layerForm">
                        <div class='layui-item'>
                            <div class='layui-inline'>
                                <label class='layui-form-label'>查询姓名</label>
                                <div class='layui-input-block'>
                                    <input type='text' placeholder='请输入姓名或工号' name='search' autocomplete="off" class='layui-input' data-id="">
                                    <ul class='layerOpen_ul_list'></ul>
                                </div>
                            </div>
                        </div>
                    </form>
                `,
                btn: ['确认', '取消'],
                skin: 'my-skin',
                success: function () {
                    form.render();
                },
                yes: function (index, layero) {
                    var employeeId = $('input[name=search]').data('id');
                    var jobNumber = $('input[name=search]').data('number');
                    var employeeName = $('input[name=search]').val();
                    let html = `<tr class="new" data-id=''>
                        <td class="index">${Number($('#accounts tbody tr').length)+1}</td>
                        <td class="employeeId" data-id="${employeeId}">${employeeName == null ? "" : employeeName}</td>
                        <td>${jobNumber == null ? "" : jobNumber}</td>
                        <td class="totalAccounts" data-total=""><input class="layui-input" type='number' name='account' min="0" value=""></td>
                        <td><input id="t${parseInt(Math.random() * 1e13)}" class="layui-input" type='text' name='separateTime' value=""></td>
                        <td></td>
                        <td><textarea class='layui-input' name="remark"></textarea>
                        </td>
                        <td></td>
                        <td></td>
                        <td><button class='remove layui-btn layui-btn-danger' type='button'>删除</button></td>
                    </tr>`

                    let append = true;
                    $('#accounts tbody td.employeeId').each(function(i,e){
                        if ($(this).data('id') == employeeId){
                            append = false;
                        }
                    })
                    if (append){
                        $('#accounts tbody').append(html);
                        $('input[name=separateTime]').each(function(){
                            let id = $(this).attr('id');
                            laydate.render({elem: `#${id}`,max:0});
                        })
                    }
                    layer.closeAll();
                }
            })
        });

        $('button.save').on('click',function(){
            var data = [];
            var accountLists = $('tr.new');
            for (var i = 0; i < accountLists.length; i++) {

                let employeeId = $(accountLists[i]).find('td.employeeId').data('id');
                let account = $(accountLists[i]).find('input[name=account]').val();
                let remark = $(accountLists[i]).find('textarea[name=remark]').val();
                let id = $(accountLists[i]).data('id');
                if (employeeId != ''&& account != ''){
                    let list = {
                        employeeId: Number(employeeId),
                        account: Number(account),
                        remark: remark,
                        id: id,
                        batch: Number(batch),
                    };
                    data.push(list);
                }
            }
            if (data.length === 0) {
                layer.msg('请确认班组成员分账信息是否填写完整!');
                return;
            }else{
                $.ajax({
                    type: 'post',
                    url: url + '/project/project/addAccount',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        data: data,
                        projectId: projectId,
                        areaId: areaId,
                        sectionId: sectionId,
                        groupId: groupId,
                        token: getToken()
                    }),
                    beforeSend:function(){
                        $('button.save').addClass('layui-btn-disabled')
                    },
                    success: function (r) {
                        if (r.code == 100000) {
                            tips('添加班组分账记录', r);
                            setTimeout(function () {
                                layer.closeAll();
                                location.reload();
                            }, 1000)
                        } else {
                            tips('添加班组分账记录', r);
                        }
                    },
                    complete:function(){
                        $('button.save').removeClass('layui-btn-disabled')
                    }
                })
            }
        });

        //输入框自动计算分账总金额
        $('body').on('input propertychange', 'input[name=account]', function () {
            $(this).parent().data('total',Number($(this).val()));
            totalPrice();
        });

        //备注的文本域，自动调整适应段落高度
        $('body').on('input', 'textarea', function () {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + "px";
        });

        function totalPrice () {
            let totalPrice = 0;
            let html = '';
            $('#accounts td.totalAccounts').each(function(){
                totalPrice += Number($(this).data('total'))
            });
            if (totalPrice > $('#total').data('total')){
                html = `<span style="color:#FF5722;font-weight: 800">${numberFormat(totalPrice, 'currency')}</span>`
                $('button.save').addClass('layui-btn-disabled');
            }else{
                html = numberFormat(totalPrice, 'currency');
                $('button.save').removeClass('layui-btn-disabled');
            }
            $('th#totalAccounts').empty().html(html)
        }

        function labelStatistics(data) {
            let html = '<div class="label">施工项分类合计：';
            let labelId = [];
            let labelList = [];
            $.each(data, function (i, e) {
                if (data[i].labelId != null) {
                    if (labelId.indexOf(data[i].labelId) === -1) {
                        labelId.push(data[i].labelId);
                        labelList.push({
                            labelId: data[i].labelId,
                            labelName: data[i].labelName,
                            account: Number(data[i].totalPrice)
                        });
                    } else {
                        let index = labelId.indexOf(data[i].labelId)
                        labelList[index].account += Number(data[i].totalPrice);
                    }
                }
            });
            $.each(labelList, function (i, e) {
                html += `<p>${labelList[i].labelName}：${numberFormat(labelList[i].account, 'currency')}</p>`;
            });
            return html;
        }
    });
</script>

</html>